package kuang.producer_consumer;

public class Test {

    public static void main(String[] args) {
        Data data = new Data();

        new Thread(() -> {
            try {
                for(int i = 0; i < 10; i++){
                    data.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "producer").start();

        new Thread(() -> {
            try {
                for(int i = 0; i < 10; i++){
                    data.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "consumer").start();

        new Thread(() -> {
            try {
                for(int i = 0; i < 10; i++){
                    data.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "producer2").start();

        new Thread(() -> {
            try {
                for(int i = 0; i < 10; i++){
                    data.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "consumer2").start();

    }
}


class Data{

    private int number;

    public synchronized void increment() throws InterruptedException {
        //使用while代替if，可以解决 虚假唤醒 的问题
        while(number != 0){
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "-->" + number);
        //通知其他线程
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        while(number == 0){
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "-->" + number);
        this.notifyAll();
    }
}
